package com.skybai.output;

import com.skybai.bean.ZtProject;
import com.skybai.common.ConfigUtil;
import com.skybai.common.QueryUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.IOException;
import java.util.Scanner;


public class Print {
    private static final Logger log = LoggerFactory.getLogger(Print.class);

//    public static void outputToPrinter(String ip) {
//        try (Socket socket = new Socket(ip, 9100)) {
//            OutputStream out = socket.getOutputStream();
//            try (FileInputStream fis = new FileInputStream(ConfigUtil.file)) {
//                //建立数组
//                byte[] buf = new byte[1024];
//                int len = 0;
//                //判断是否读到文件末尾
//                while ((len = fis.read(buf)) != -1) {
//                    out.write(buf, 0, len);
//                }
//                //告诉服务端，文件已传输完毕
//                socket.shutdownOutput();
//            }
//        } catch (Exception e) {
//            log.error("文件打印错误");
//            e.printStackTrace();
//        }
//    }
//
//    public static void defaultPrintPDF() throws Exception {
//        // 构建打印请求属性集
//        HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
//        // 设置打印格式，因为未确定类型，所以选择autosense
//        //DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
//        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
//        log.info("打印文件类型为：===================" + flavor);
//        pras.add(MediaName.ISO_A4_TRANSPARENT);//A4纸张
//        //遍历
//        PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
//
//        for (PrintService printService2 : printService) {
//            log.info("本机可使用打印机列表：===================" + printService2);
//        }
//        //定位默认的打印服务
//        PrintService defaultService = PrintServiceLookup
//                .lookupDefaultPrintService();
//        log.info("打印工具选择打印机为：===================" + defaultService);
//        try {
//            DocPrintJob job = defaultService.createPrintJob(); // 创建打印作业
//            FileInputStream fis = new FileInputStream(ConfigUtil.file); // 构造待打印的文件流
//            DocAttributeSet das = new HashDocAttributeSet();
//            Doc doc = new SimpleDoc(fis, flavor, das);
//            job.print(doc, pras);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.info("打印异常", e);
//            throw new Exception();
//        }
//    }
//
//    public static void printImage(String printerName) {
//        InputStream fis = null;
//        try {
//            // 设置打印格式，如果未确定类型，可选择autosense
//            DocFlavor flavor = DocFlavor.INPUT_STREAM.PDF;
//            // 设置打印参数
//            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
//            aset.add(new Copies(1)); //份数
//            //aset.add(MediaSize.ISO.A4); //纸张
//            // aset.add(Finishings.STAPLE);//装订
//            aset.add(Sides.DUPLEX);//单双面
//            // 定位打印服务
//            PrintService printService = null;
//            if (printerName != null) {
//                //获得本台电脑连接的所有打印机
//                PrintService[] printServices = PrinterJob.lookupPrintServices();
//                if (printServices == null || printServices.length == 0) {
//                    System.out.print("打印失败，未找到可用打印机，请检查。");
//                    return;
//                }
//                //匹配指定打印机
//                for (int i = 0; i < printServices.length; i++) {
//                    System.out.println(printServices[i].getName());
//                    if (printServices[i].getName().contains(printerName)) {
//                        printService = printServices[i];
//                        break;
//                    }
//                }
//                if (printService == null) {
//                    System.out.print("打印失败，未找到名称为" + printerName + "的打印机，请检查。");
//                    return;
//                }
//            }
//            fis = new FileInputStream(ConfigUtil.file); // 构造待打印的文件流
//            Doc doc = new SimpleDoc(fis, flavor, null);
//            DocPrintJob job = printService.createPrintJob(); // 创建打印作业
//            job.print(doc, aset);
//        } catch (FileNotFoundException | PrintException e1) {
//            e1.printStackTrace();
//        } finally {
//            // 关闭打印的文件流
//            if (fis != null) {
//                try {
//                    fis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }

    public static void pdfPrint(String printerName) throws Exception {
        PDDocument document = null;
        try {
            document = PDDocument.load(ConfigUtil.file);
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setJobName(ConfigUtil.file.getName());
            if (printerName != null) {
                // 查找并设置打印机
                //获得本台电脑连接的所有打印机
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if(printServices == null || printServices.length == 0) {
                    System.out.print("打印失败，未找到可用打印机，请检查。");
                    return ;
                }
                PrintService printService = null;
                //匹配指定打印机
                for (int i = 0;i < printServices.length; i++) {
                    System.out.println(printServices[i].getName());
                    if (printServices[i].getName().contains(printerName)) {
                        printService = printServices[i];
                        break;
                    }
                }
                if(printService!=null){
                    printJob.setPrintService(printService);
                }else{
                    System.out.print("打印失败，未找到名称为" + printerName + "的打印机，请检查。");
                    return ;
                }
            }
            //设置纸张及缩放
            PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
            //设置多页打印
            Book book = new Book();
            PageFormat pageFormat = new PageFormat();
            //设置打印方向
            //纵向
            pageFormat.setOrientation(PageFormat.PORTRAIT);
            //设置纸张
            pageFormat.setPaper(getPaper());
            book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
            printJob.setPageable(book);
            //设置打印份数
            printJob.setCopies(1);
            //添加打印属性
            HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
            //设置单双页
            pars.add(Sides.ONE_SIDED);
            printJob.print(pars);
        }finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static Paper getPaper() {
        Paper paper = new Paper();
        // 默认为A4纸张，对应像素宽和高分别为 595, 842
        int width = 595;
        int height = 842;
        // 设置边距，单位是像素，10mm边距，对应 28px
        int marginLeft = 10;
        int marginRight = 0;
        int marginTop = 10;
        int marginBottom = 0;
        paper.setSize(width, height);
        // 下面一行代码，解决了打印内容为空的问题
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        return paper;
    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int projectId;
        while(true){
            System.out.println("请输入项目编号");
            projectId = sc.nextInt();
            ZtProject project = QueryUtil.getProject(projectId);
            if(project == null){
                System.out.println("没有此项目，请重新输入");
            }else{
                System.out.println("项目名称为 【" + project.getName() + "】 ,确认请输入【Y】");
                String res = sc.next();
                if("Y".equals(res) || "y".equals(res)){
                    break;
                }
            }
        }

        int i;
        do{
            System.out.println("请选择打印类型： 1、全部打印  2、部分打印");
            i = sc.nextInt();
        }while(i != 1 && i != 2);

        if(i == 1){
            group(projectId, QueryUtil.ALL_PRINT);
        }else{
            int printOption;
            do {
                System.out.println("请输入打印内容: 1、需求 2、任务 3、BUG");
                printOption = sc.nextInt();
            } while (printOption != 1 && printOption != 2 && printOption != 3);

            int k;
            do{
                System.out.println("请选择打印方式: 1、全部打印  2、按人员打印");
                k = sc.nextInt();
            } while (k != 1 && k != 2);

            if(k == 1){
                group(projectId, printOption);
            }else{
                QueryUtil.showMember(projectId, printOption);
                System.out.println("请输入员工编号");
                int userId = sc.nextInt();
                System.out.println("确认打印请输入【Y】");
                String res = sc.next();

                if("Y".equals(res) || "y".equals(res)){
                    OutputToFile.printUserContent(projectId, printOption, userId);
                    //pdfPrint("Brother MFC-7880DN Printer");
                }else{
                    System.out.println("打印已取消，程序退出");
                }
            }
        }

        //OutputToFile.outputToPDF();
        //pdfPrint("Brother MFC-7880DN Printer");
    }

    private static void group(int projectId, int printOption) {
        Scanner sc = new Scanner(System.in);
        int j;
        do{
            System.out.println("请选择分组方式: 1、顺序打印  2、人员分组");
            j = sc.nextInt();
        }while(j != 1 && j != 2);


        System.out.println("确认打印请输入【Y】");
        String res = sc.next();

        if("Y".equals(res) || "y".equals(res)){
            if(j == 1){
                OutputToFile.print(projectId, printOption);
            }else {
                OutputToFile.printGroupByPerson(projectId, printOption);
            }
            try {
                //pdfPrint("Brother MFC-7880DN Printer");
            } catch (Exception e) {
                log.error("文件打印出错");
                e.printStackTrace();
            }
        }else{
            System.out.println("打印已取消，程序退出");
        }
    }

}
